#include <iostream>
#include <algorithm>
#include <vector>
#include <limits.h>
using namespace std;
class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {

            int len = nums.size();
            if (len < 3) {
                return 0;
            }
            if (len == 3) {
                return nums[0] + nums[1] + nums[2];
            }

            sort(nums.begin(), nums.end());

            int closest = INT_MAX;
            int value = 0;
            int i=0;
            while(i<len-2) {
                int j=len-1;
                while(j>i+1) {
                    for (int m=i+1; m<j; m++) {
                        int val = nums[i]+nums[j]+nums[m];
                        if (val == target) {
                            return target;
                        } else {
                            if (abs(val-target) < closest) {
                                closest = abs(val-target);
                                value = val;
                            }
                        }
                    }
                    j--;
                }
                i++;
            }

            return value;
        }
};

int main() {

    Solution s;
    vector<int> nums = {-1, 2, 1, -4};
    int target = 1;

    cout << s.threeSumClosest(nums, target) << endl;


}
